<?php

class WidgetFormAutocomplete extends sfWidgetForm
{

	public function configure($options = array(), $attributes = array())
	{

		$this->addRequiredOption('action', '');
		$this->addRequiredOption('model', '');
		$this->addOption('multiple', false);
		$this->addOption('filter', false);
		$this->addOption('plural', 'Elementos');
		$this->addOption('values', array());
		$this->addOption('template',
<<<EOF
  <input type="text" id="{input.id}" value="{input.value}" class="{input.class} txt_buscar">
  <a class="clear" href="" style="position: relative; top: 4px; left: -25px; text-decoration: none;" title="Reiniciar">
    <span class="clear_bg_loading"></span>
    <span class="clear_bg"></span>
  </a>
EOF
		);

		$this->addOption('template.multiple',
<<<EOF
  <br>
  <span>{plural} que están en la lista:</span>
  <a href="" class="remove_bg"  onclick="eliminaItems(this); return false;" style="position: relative; top: 4px;" title="Eliminar ítems seleccionados">
  </a>
  <br>
{select}

EOF
		);

		$this->addOption('template.javascript',
<<<EOF

  <script type="text/javascript">
  $(function() {
    $('#{input.id}').autocomplete({
      source: buscaItems,
      minLength: 4,
      delay: 500,
      url: '{url}',
      targetId: '{target.id}',
      select: agregaItems
    });
  });
  </script>

EOF
		);

	}

	public function getJavascripts()
	{
		return array('/js/autocomplete.js');
	}

	public function render($name, $value = null, $attributes = array(), $errors = array())
	{
		$id = $this->generateId($name);
		
		$template_vars = array(
			'{target.id}' => $id . '_target',
			'{target.name}' => $this->getOption('multiple') || $this->getOption('filter') ? $name . '[]' : $name,
			'{input.id}' => $id . '_buscar',
			'{input.value}' => '',
			'{input.class}' => $this->getOption('filter') ? 'buscar_filtro' : 'buscar_form',
			'{url}' => sfContext::getInstance()->getController()->genUrl($this->getOption('action')),
			'{plural}' => $this->getOption('plural')
		);

		$list = array();

		if (!empty($value))
		{
			$list = $this->getOption('values');
			if (empty($list))
				$list = Doctrine_Core::getTable($this->getOption('model'))->createQuery()->whereIn('id', $value)->execute();
		}

		$widget_data = $this->getOption('template.javascript') . $this->getOption('template');
		$attributes['id'] = $template_vars['{target.id}'];
		$attributes['name'] = $template_vars['{target.name}'];

		if ($this->getOption('multiple'))
		{
			$options = array();
			foreach ($list as $result)
			{
				$opt_attr = array();
				$opt_attr['value'] = $result->getId();
				$options[] = $this->renderContentTag('option', $result->__toString(), $opt_attr);
			}

			$attributes['multiple'] = 'multiple';
			$attributes['class'] = 'select_multiple';

			$select = $this->renderContentTag('select', "\n" . implode("\n",$options) . "\n", $attributes);

			$template_vars['{select}'] = $select;
			
			$widget_data = $widget_data . '<br>' . $this->getOption('template.multiple');
		}
		else
		{
			$attributes['type'] = 'hidden';
			$attributes['value'] = $value;
			$template_vars['{input.value}'] = isset($list[0]) ? $list[0]->__toString() : '';

			$widget_data = $widget_data . $this->renderTag('input', $attributes);
		} 

		return strtr($widget_data, $template_vars);
	}

}
